﻿using System;
using System.Web.Http;
using eCommMongo.Core;
using eCommMongo.Service.Customers;
using eCommMongo.Service.Pictures;
using yiCommerce.Core;
using yiCommerce.Service.Messages;

namespace eCommMongo.Web.Controllers.api
{
    public class CropInfo
    {
        public string PictureId { get; set; }
        public int X { get; set; }
        public int Y { get; set; }
        public int W { get; set; }
        public int H { get; set; }

        public int CustomerLogId { get; set; }
    }
    public class CropImageController : ApiController
    {
        private IPictureService _pictureService;
        private ICustomerService _customerService;
        private IWorkContext _workContext;
        private IMessageService _messageService;
        public CropImageController(IPictureService pictureService, ICustomerService customerService, IWorkContext workContext, IMessageService messageService)
        {
            _pictureService = pictureService;
            _customerService = customerService;
            _workContext = workContext;
            _messageService = messageService;
        }

        public CropImageResult Crop(CropInfo cropInfo)
        {
            var result = new CropImageResult();


            try
            {

                var pic = _pictureService.GetPictureById(cropInfo.PictureId);

                var bytes = _pictureService.CropImage(cropInfo.PictureId, cropInfo.X, cropInfo.Y, cropInfo.W, cropInfo.H);

                var picture = _pictureService.InsertPicture(bytes, pic.MimeType, null, true);
                //var pictureUrl = _pictureService.GetPictureUrl(picture.Id,  0,true);

                _customerService.UpdateCustomerLogo(_workContext.CurrentCustomer.Id,
                                                       picture.Id);

                var newSizePicUrl = _pictureService.GetPictureUrl(picture, 0, true);

                result.Status = ConstInfo.ResultSuccessStatus;
                result.NewPicUrl = newSizePicUrl;
                result.Message = _messageService.GetResourceValue(Messages.CustomerLogo_Update_Successfully, 0);
            }
            catch (Exception e)
            {
                result.Status = ConstInfo.ResultFailedStatus;
                result.Message = e.Message;
            }

            return result;

        }
    }

    public class CropImageResult
    {
        public string Status { get; set; }
        public string Message { get; set; }
        public string NewPicUrl { get; set; }
    }
}
